package com.sojson.util.security.shiro.realm.impl;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;

import com.sojson.config.exception.TransErrorCode;
import com.sojson.enums.core.ERoleType;
import com.sojson.project.sys.user.entity.vo.UserVo;
import com.sojson.util.ExpUtil;
import com.sojson.util.StringUtil;
import com.sojson.util.enums.ELoginOtherType;
import com.sojson.util.security.shiro.realm.AbstractCustomAuthorizingRealm;
import com.sojson.util.security.shiro.token.CustomToken;
import com.sojson.util.token.Token;
import com.sojson.util.token.TokenUtil;

/**
 * ShiroRealm
 * 
 * @author liu
 * @date 2020-08-05
 */
public class ShiroRealm extends AbstractCustomAuthorizingRealm {

    // @Autowired
    // private UserServce userServce;

    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken autheToken) {
        CustomToken customToken = (CustomToken)autheToken;
        // 登录的类型
        Integer loginType = customToken.getLoginType();
        // 获取到的密码
        String pwd = null;

        // 通过帐号查找用户
        UserVo user = null;
        Set<String> hashSet = new HashSet<>();
        hashSet.add(ERoleType.USER.getKey());
        // user = userServce.findByRoleMobile(hashSet, customToken.getUsername());
        // 用户不存在
        if (StringUtil.isBlankObject(user)) {
            ExpUtil.throwEx(TransErrorCode.NOT_USER);
        }
        // pwd = user.getPwd();

        // 判断登录的用户是否被禁用
        boolean submitLoginIsDisable = TokenUtil.submitLoginIsDisable(user);
        if (submitLoginIsDisable) {
            ExpUtil.throwEx("对不起,您的账号已停用");
        }

        // 帐号密码登录
        if (ELoginOtherType.GENERAL.getCode() == loginType) {
            // 密码错误
            if (!customToken.getPwd().equals(pwd)) {
                ExpUtil.throwEx(TransErrorCode.ERR_PWD);
            }
        } else if (ELoginOtherType.MOBILE.getCode() == loginType) {
            // 短信登录
            pwd = customToken.getPwd();
        }

        // 给用户赋初值
        // TokenUtil.userLoginInitOther(user, user);

        // param1:从数据库中查询到的用户对象
        // param2:从数据库中查询到的密码
        // param3:当前类名
        Token token = null;
        try {
            token = TokenUtil.getToken(true);
            token.setUser(user);
        } catch (IOException e) {
            ExpUtil.throwEx(e);
        }
        return new SimpleAuthenticationInfo(token, pwd, this.getName());
    }

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
        // TODO Auto-generated method stub
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // String username = TokenUtil.getUsername();
        //
        // // 根据用户ID查询权限（permission）,放入到Authorization里。
        // Set<String> permissions = new HashSet<>();
        // permissions.add(username);
        // info.setStringPermissions(permissions);
        //
        // // 根据用户ID查询角色（role）,放入到Authorization里。
        // Set<String> roles = new HashSet<>();
        // roles.add(username);
        // info.setRoles(roles);

        return info;
    }

    // /**
    // * 清空当前用户权限信息
    // */
    // public void clearCachedAuthorizationInfo() {
    // SimplePrincipalCollection principals = new SimplePrincipalCollection(TokenUtil.getPrincipal(), getName());
    // super.clearCachedAuthorizationInfo(principals);
    // }

    /**
     * 指定principalCollection 清除
     * principalCollection((UUser)SecurityUtils.getSubject().getPrincipal())是用户,可从redis中获取
     */
    @Override
    public void clearCachedAuthorizationInfo(PrincipalCollection principalCollection) {
        SimplePrincipalCollection principals = new SimplePrincipalCollection(principalCollection, getName());
        super.clearCachedAuthorizationInfo(principals);
    }

}